package com.chen.controller;

import com.chen.entity.LoginUser;
import com.chen.entity.Result;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {
    //注入DefaultKaptcha的bean对象 ——— 生成验证码图片
    @Resource(name = "captchaProducer")
    private Producer producer;

    //注入redis模板
    @Autowired
    private StringRedisTemplate redisTemplate;

    //生成验证码的url接口/captcha/captchaImage
    @RequestMapping("/captcha/captchaImage")
    public void captchaImage(HttpServletResponse response){
        ServletOutputStream out = null;

        try {
            //生成验证码图片的文件
            String text = producer.createText();
            //使用验证码文本生成验证码图片 ——— BufferedImage就代表验证码图片
            BufferedImage image = producer.createImage(text);
            //将验证码文本作为键保存到redis -- 设置键的过期时间，30分钟
            redisTemplate.opsForValue().set(text,"",60, TimeUnit.SECONDS);

            /**
             * 将验证码响应给前端：
             */
            //设置响应正文image/jpeg
            response.setContentType("image/jpeg");
            //将验证码图片写给前端
            out = response.getOutputStream();
            ImageIO.write(image,"jpg",out);//使用响应对象的字节输出流写入验证码图片，给前端写入
            //刷新
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭字节输出流
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     *
     * @param loginUser -- 接收并封装前端传递的登录的用户信息的json数据
     * @return 返回
     */
    @RequestMapping("/login")
    public Result login(@RequestBody LoginUser loginUser){

        return null;
    }
}
